<script setup lang="ts">
import { IconType } from '@xtail/vue3'
import ScriptConfForm from './components/script-conf-form/script-conf-form.vue'
import { genDelConfs } from './utils'

const title = PageTitleConst.ScriptConfManager

const scriptConfStore = useScriptConfStore()

const { dirTreeComputed, dirSelected, currentConfListComputed } = genDirStatus(scriptConfStore)

const { form, isShowEditor, isAdd, addConf, editConf, delConfs } = genCrudStatus<ScriptConfType>(
  genScriptConf,
  scriptConfStore,
  genDelConfs
)

const filterCondition = ref(1)
const filterText = ref('')
watch(
  () => filterCondition.value,
  () => (filterText.value = '')
)
const currentConfListFilterComputed = computed(() => {
  if (!filterText.value) return currentConfListComputed.value
  if (filterCondition.value === 1) {
    return currentConfListComputed.value.filter((item) => item.label.includes(filterText.value))
  } else {
    return currentConfListComputed.value.filter((item) => item.cmd.includes(filterText.value))
  }
})

const router = useRouter()
const goEditScriptConf = (id: string) => {
  scriptConfStore.setScriptConfSelected(id)
  router.push({ name: RouteNameConst.EditScript })
}
</script>

<template>
  <page-side-responsive :title="title" :content-grid="currentConfListFilterComputed.length > 0">
    <template #actions="{ collapse }">
      <div class="flex items-center gap-2">
        <reload-btn :click="() => scriptConfStore.load()" />
        <add-btn :collapse="collapse" :click="addConf" />
      </div>
    </template>
    <template #side>
      <dir-tree
        :data="dirTreeComputed"
        :current-node="dirSelected"
        :click="(id) => (dirSelected = id)"
        :edit="editConf"
        :del="delConfs"
      />
    </template>
    <template #content-top>
      <div class="px-4 pt-4">
        <el-input v-model="filterText" placeholder="搜索脚本..." clearable>
          <template #prepend>
            <el-select v-model="filterCondition" class="!w-18">
              <el-option label="名称" :value="1" />
            </el-select>
          </template>
        </el-input>
      </div>
    </template>
    <template #content>
      <card
        v-for="item in currentConfListFilterComputed"
        :key="item.value"
        :title="item.label"
        :sub-title="item.cmd"
        :icon="item.icon as IconType"
        :icon-color="item.color"
        :edit="() => editConf(item._id as string)"
        :del="(cascade) => delConfs(item._id as string, cascade)"
        @click="() => goEditScriptConf(item._id as string)"
      />
      <el-empty v-if="!currentConfListFilterComputed.length" />
    </template>
  </page-side-responsive>
  <drawer-responsive
    v-model="isShowEditor"
    :title="isAdd ? '新增命令配置(目录)' : '编辑命令配置(目录)'"
  >
    <script-conf-form :form="form" :success="() => (isShowEditor = false)" />
  </drawer-responsive>
</template>

<style scoped></style>
